<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>抢答人端 - 抢答器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%);
            color: white;
            height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .container {
            width: 100%;
            max-width: 500px;
            text-align: center;
        }
        h1 {
            margin-bottom: 30px;
            font-size: 2.2rem;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }
        .player-id {
            font-size: 1.5rem;
            margin-bottom: 20px;
            background: rgba(255, 255, 255, 0.2);
            padding: 10px 20px;
            border-radius: 50px;
            display: inline-block;
        }
        .status-panel {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            min-height: 120px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .status-text {
            font-size: 1.8rem;
            font-weight: bold;
        }
        .answer-btn {
            width: 200px;
            height: 200px;
            border-radius: 50%;
            background: #ff4757;
            color: white;
            border: none;
            font-size: 1.8rem;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto;
        }
        .answer-btn:disabled {
            background: #57606f;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .answer-btn:not(:disabled):hover {
            transform: scale(1.05);
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4);
        }
        .answer-btn:not(:disabled):active {
            transform: scale(0.95);
        }
        .connection-status {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
        }
        .connected {
            background: rgba(76, 175, 80, 0.8);
        }
        .disconnected {
            background: rgba(244, 67, 54, 0.8);
        }
        .success {
            color: #2ed573;
        }
        .fail {
            color: #ff6b6b;
        }
    </style>
</head>
<body>
<div class="connection-status disconnected" id="connectionStatus">未连接</div>
<!-- 添加到 <body> 标签内，靠近其他元素的位置 -->
<audio id="answerSound" src="/uploads/20251107/1eab509df800f380b2590e992d43ee9a.mp3" preload="auto"></audio>
<div class="container">
    <h1>抢答人端</h1>

    <div class="player-id">编号: <span id="playerId">--</span></div>

    <div class="status-panel">
        <div class="status-text" id="statusText">等待开始</div>
    </div>

    <button class="answer-btn" id="answerBtn" disabled>抢答</button>
</div>

<script>
    class PlayerClient {
        constructor() {
            this.ws = null;
            this.connected = false;
            this.status = 0; // 0:未开始 1:抢答中 2:已结束
            this.playerId = null;
            this.winnerId = null;

            this.init();
        }

        init() {
            this.generatePlayerId();
            this.connect();
            this.bindEvents();
        }

        generatePlayerId() {
            // 尝试从本地存储获取玩家ID
            let storedId = localStorage.getItem('answer_player_id');
            if (storedId) {
                this.playerId = storedId;
            } else {
                // 生成新的玩家ID (示例: P001, P002...)
                const randomId = 'P' + Math.floor(100 + Math.random() * 900);
                this.playerId = randomId;
                localStorage.setItem('answer_player_id', randomId);
            }

            document.getElementById('playerId').textContent = this.playerId;
        }

        connect() {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//${window.location.hostname}/wss`;

            this.ws = new WebSocket(wsUrl);

            this.ws.onopen = () => {
                console.log('WebSocket连接已建立');
                this.connected = true;
                this.updateConnectionStatus();
                this.loginAsPlayer();
            };

            this.ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                this.handleMessage(data);
            };

            this.ws.onclose = () => {
                console.log('WebSocket连接已关闭');
                this.connected = false;
                this.updateConnectionStatus();

                // 5秒后尝试重连
                setTimeout(() => {
                    this.connect();
                }, 5000);
            };

            this.ws.onerror = (error) => {
                console.error('WebSocket错误:', error);
                this.connected = false;
                this.updateConnectionStatus();
            };
        }

        bindEvents() {
            document.getElementById('answerBtn').addEventListener('click', () => {
                this.answer();
            });
        }

        loginAsPlayer() {
            this.sendMessage({
                type: 'player_login',
                player_id: this.playerId
            });
        }

        answer() {
            // 播放音效
            const sound = document.getElementById('answerSound');
            if (sound) {
                sound.currentTime = 0; // 重置音频到开头
                sound.play().catch(e => console.log('音频播放失败:', e));
            }


            this.sendMessage({
                type: 'player_answer',
                player_id: this.playerId
            });
        }

        sendMessage(message) {
            if (this.connected && this.ws.readyState === WebSocket.OPEN) {
                this.ws.send(JSON.stringify(message));
            }
        }

        handleMessage(data) {
            switch (data.type) {
                case 'status_update':
                    this.status = data.status;
                    this.winnerId = data.winner_id;
                    this.playerId = data.player_id || this.playerId;
                    this.round = data.round || this.round;
                    document.getElementById('playerId').textContent = this.playerId;
                    this.updateUI();
                    break;
                case 'game_started':
                    this.status = 1;
                    this.winnerId = null;
                    this.updateUI();
                    break;
                case 'game_result':
                    this.status = 2;
                    this.winnerId = data.winner_id;
                    this.updateUI();
                    break;
                case 'game_reset':
                    this.status = 0;
                    this.winnerId = null;
                    this.round = data.round || this.round + 1;
                    this.updateUI();
                    break;
            }
        }

        updateUI() {
            const statusText = document.getElementById('statusText');
            const answerBtn = document.getElementById('answerBtn');

            // 重置状态文本样式
            statusText.className = 'status-text';

            switch (this.status) {
                case 0:
                    statusText.textContent = '等待开始';
                    answerBtn.disabled = true;
                    answerBtn.textContent = '抢答';
                    break;
                case 1:
                    statusText.textContent = '抢答中!';
                    answerBtn.disabled = false;
                    answerBtn.textContent = '抢答';
                    break;
                case 2:
                    answerBtn.disabled = true;
                    answerBtn.textContent = '抢答';

                    if (this.winnerId === this.playerId) {
                        statusText.textContent = '抢答成功!';
                        statusText.className = 'status-text success';
                    } else if (this.winnerId) {
                        statusText.textContent = '抢答失败!';
                        statusText.className = 'status-text fail';
                    } else {
                        statusText.textContent = '抢答结束';
                    }
                    break;
            }
        }

        updateConnectionStatus() {
            const statusElement = document.getElementById('connectionStatus');
            if (this.connected) {
                statusElement.textContent = '已连接';
                statusElement.className = 'connection-status connected';
            } else {
                statusElement.textContent = '未连接';
                statusElement.className = 'connection-status disconnected';
            }
        }
    }

    // 初始化客户端
    document.addEventListener('DOMContentLoaded', () => {
        new PlayerClient();
    });
</script>
</body>
</html>